<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-input
        v-model="goodsName"
        placeholder="请输入产物名"
        clearable
        style="width: 200px"
        @keyup.enter.native="loadPost"
      ></el-input>

      <div
        style="display: inline-flex; flex-direction: column; margin-left: 5px"
      >
        <el-select
          v-model="storageId"
          clearable
          placeholder="请选择仓库"
          style="margin-bottom: 5px"
        >
          <el-option
            v-for="item in storageData"
            :key="item.id"
            :label="item.storageName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="goodsTypeId"
          clearable
          placeholder="请选择分类"
          style="margin-bottom: 5px"
        >
          <el-option
            v-for="item in goodstypeData"
            :key="item.id"
            :label="item.goodsTypeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-select v-model="sourceId" clearable placeholder="请选择产地">
          <el-option
            v-for="item in sourceData"
            :key="item.id"
            :label="item.sourceName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>

      <el-button type="primary" style="margin-left: 5px" @click="loadPost"
        >查询 <i class="el-icon-search"></i
      ></el-button>
      <el-button type="warning" style="margin-left: 5px" @click="resetParam"
        >重置表单 <i class="el-icon-refresh"></i
      ></el-button>
      <el-button
        type="primary"
        style="margin-left: 5px"
        @click="add"
        v-if="user.roleId != 1"
        >新增 <i class="el-icon-circle-plus-outline"></i
      ></el-button>
      <el-button
        type="primary"
        style="margin-left: 5px"
        @click="inGoods"
        v-if="user.roleId != 1"
        >入库 <i class="el-icon-bottom-left"></i
      ></el-button>
      <el-button
        type="primary"
        style="margin-left: 5px"
        @click="outGoods"
        v-if="user.roleId != 1"
        >出库 <i class="el-icon-top-right"></i
      ></el-button>
    </div>
    <el-table
      v-loading="isLoading"
      :data="tableData"
      :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
      border
      style="min-height: 484px"
      highlight-current-row
      @current-change="selectCurrentChange"
    >
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column prop="avatarUrl" label="图片" width="60">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center">
            <el-image
              style="width: 30px; height: 30px; border-radius: 50%"
              v-if="scope.row.avatarUrl"
              :src="scope.row.avatarUrl"
              :preview-src-list="[scope.row.avatarUrl]"
            ></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="goodsName"
        label="物品名"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="storageId"
        label="仓库"
        width="120"
        :formatter="formatStorage"
      >
      </el-table-column>
      <el-table-column
        prop="goodstypeId"
        label="分类"
        width="120"
        :formatter="formatGoodstype"
      >
      </el-table-column>
      <el-table-column
        prop="sourceId"
        label="产地"
        width="120"
        :formatter="formatSource"
      >
      </el-table-column>
      <el-table-column prop="count" label="数量" width="80"></el-table-column>
      <el-table-column prop="remark" label="备注" width="200"></el-table-column>
      <el-table-column
        prop="operate"
        label="操作"
        width="1000"
        v-if="user.roleId != 2"
      >
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)"
            >编辑 <i class="el-icon-edit"></i
          ></el-button>
          <el-popconfirm
            title="确定删除吗？"
            @confirm="del(scope.row.id)"
            style="margin-left: 5px"
          >
            <el-button slot="reference" size="small" type="danger"
              >删除<i class="el-icon-remove-outline"></i
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      title="产物信息维护"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8090/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.avatarUrl" :src="form.avatarUrl" alt="" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="产物名" prop="goodsName">
          <el-col :span="20">
            <el-input v-model="form.goodsName"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="仓库" prop="storageId">
          <el-col :span="20">
            <el-select
              v-model="form.storageId"
              placeholder="请选择仓库"
              style="margin-left: 5px"
            >
              <el-option
                v-for="item in storageData"
                :key="item.id"
                :label="item.storageName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="分类" prop="goodsTypeId">
          <el-col :span="20">
            <el-select
              v-model="form.goodsTypeId"
              placeholder="请选择分类"
              style="margin-left: 5px"
            >
              <el-option
                v-for="item in goodstypeData"
                :key="item.id"
                :label="item.goodsTypeName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="产地" prop="sourceId">
          <el-col :span="20">
            <el-select
              v-model="form.sourceId"
              placeholder="请选择产地"
              style="margin-left: 5px"
            >
              <el-option
                v-for="item in sourceData"
                :key="item.id"
                :label="item.sourceName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="数量" prop="count">
          <el-col :span="20">
            <el-input v-model="form.count"></el-input>
          </el-col>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-col :span="20">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="form1.action === '1' ? '入库' : '出库'"
      :visible.sync="inDialogVisible"
      width="30%"
      center
    >
      <el-dialog
        width="75%"
        title="用户选择"
        :visible.sync="innerVisible"
        append-to-body
      >
        <SelectUser @doSelectUser="doSelectUser"></SelectUser>
        <span slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmUser">确 定</el-button>
        </span>
      </el-dialog>

      <el-form ref="form1" :rules="rules1" :model="form1" label-width="80px">
        <el-form-item label="产物名">
          <el-col :span="20">
            <el-input v-model="form1.goodsname" readonly></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="申请人">
          <el-col :span="20">
            <el-input
              v-model="form1.username"
              readonly
              @click.native="selectUser"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-col :span="20">
            <el-input v-model="form1.count"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="20">
            <el-input type="textarea" v-model="form1.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doInGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectUser from './user/SelectUser.vue'

export default {
  name: 'Goods',
  components: { SelectUser },
  data() {
    let checkCount = (rule, value, callback) => {
      if (value > 9999) {
        callback(new Error('数量输入过大'))
      } else {
        callback()
      }
    }

    return {
      user: JSON.parse(localStorage.getItem('curUser')) || {},
      storageData: [],
      goodstypeData: [],
      sourceData: [],
      tableData: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      goodsName: '',
      storageId: '',
      goodsTypeId: '',
      sourceId: '',
      centerDialogVisible: false,
      inDialogVisible: false,
      innerVisible: false,
      currentRow: {},
      tempUser: {},
      form: {
        id: '',
        avatarUrl: '',
        goodsName: '',
        storageId: '',
        goodsTypeId: '',
        sourceId: '',
        count: '0',
        remark: ''
      },
      form1: {
        goodsId: '',
        goodsname: '',
        count: '',
        username: '',
        userId: '',
        adminId: '',
        remark: '',
        action: '1'
      },
      rules1: {
        count: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          {
            pattern: /^([1-9][0-9]*){1,4}$/,
            message: '数量必须为正整数字',
            trigger: 'blur'
          },
          { validator: checkCount, trigger: 'blur' }
        ]
      },
      rules: {
        goodsName: [
          { required: true, message: '请输入产物名', trigger: 'blur' }
        ],
        storageId: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
        goodsTypeId: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        sourceId: [{ required: true, message: '请选择产地', trigger: 'blur' }]
      },
      isLoading: false
    }
  },
  methods: {
    handleAvatarSuccess(res) {
      // res 就是文件的路径
      this.form.avatarUrl = res
    },
    doSelectUser(val) {
      console.log(val)
      this.tempUser = val
    },
    confirmUser() {
      this.form1.username = this.tempUser.name
      this.form1.userId = this.tempUser.id

      this.innerVisible = false
    },
    selectCurrentChange(val) {
      this.currentRow = val
    },
    formatStorage(row) {
      let temp = this.storageData.find(item => {
        return item.id == row.storageId
      })

      return temp && temp.storageName
    },
    formatGoodstype(row) {
      let temp = this.goodstypeData.find(item => {
        return item.id == row.goodsTypeId
      })

      return temp && temp.goodsTypeName
    },
    formatSource(row) {
      let temp = this.sourceData.find(item => {
        return item.id == row.sourceId
      })

      return temp && temp.sourceName
    },
    resetForm() {
      // this.$refs.form.resetFields()
      this.form = {
        id: '',
        avatarUrl: '',
        goodsName: '',
        storageId: '',
        goodsTypeId: '',
        sourceId: '',
        count: '0',
        remark: ''
      }
    },
    resetInForm() {
      // this.$refs.form1.resetFields()
      this.form1 = {
        goodsId: '',
        goodsname: '',
        count: '',
        username: '',
        userId: '',
        adminId: '',
        remark: '',
        action: '1'
      }
    },
    del(id) {
      console.log(id)

      this.$http.get('/goods/del?id=' + id).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.loadPost()
        } else {
          this.$message.error('操作失败！')
        }
      })
    },
    mod(row) {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        //赋值到表单
        this.form.id = row.id
        this.form.avatarUrl = row.avatarUrl
        this.form.goodsName = row.goodsName
        this.form.storageId = row.storageId
        this.form.goodsTypeId = row.goodsTypeId
        this.form.sourceId = row.sourceId
        this.form.count = row.count
        this.form.remark = row.remark
      })
    },
    add() {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.resetForm()

        this.form.id = ''
      })
    },
    inGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录')
        return
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm()

        this.form1.goodsname = this.currentRow.goodsName
        this.form1.goodsId = this.currentRow.id
        this.form1.adminId = this.user.id
        this.form1.action = '1'
      })
    },
    outGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录')
        return
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm()

        this.form1.goodsname = this.currentRow.goodsName
        this.form1.goodsId = this.currentRow.id
        this.form1.adminId = this.user.id
        this.form1.action = '2'
      })
    },
    selectUser() {
      this.innerVisible = true
    },
    doSave() {
      this.$http.post('/goods/save', this.form).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.centerDialogVisible = false
          this.loadPost()
          this.resetForm()
        } else {
          this.$message.error('操作失败！')
        }
      })
    },
    doMod() {
      this.$http.post('/goods/update', this.form).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.centerDialogVisible = false
          this.loadPost()
          this.resetForm()
        } else {
          this.$message.error('操作失败！')
        }
      })
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            this.doMod()
          } else {
            this.doSave()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    doInGoods() {
      this.$http.post('/record/save', this.form1).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.inDialogVisible = false
          this.loadPost()
          this.resetInForm()
        } else {
          this.$message.error('操作失败！')
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageNum = 1
      this.pageSize = val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageNum = val
      this.loadPost()
    },
    resetParam() {
      this.goodsName = ''
      this.storageId = ''
      this.goodsTypeId = ''
      this.sourceId = ''
    },
    loadPost() {
      // 开启遮罩层
      this.isLoading = true

      this.$http
        .post('/goods/listPage', {
          pageSize: this.pageSize,
          pageNum: this.pageNum,
          param: {
            goodsName: this.goodsName,
            goodsTypeId: this.goodsTypeId + '',
            storageId: this.storageId + '',
            sourceId: this.sourceId + ''
          }
        })
        .then(res => {
          setTimeout(() => {
            // 关闭遮罩层
            this.isLoading = false

            console.log(res)
            if (res.code == 200) {
              this.tableData = res.data
              this.total = res.total
            } else {
              alert('获取数据失败')
            }
          }, 300)
        })
    },
    loadStorage() {
      this.$http.get('/storage/list').then(res => {
        console.log(res)
        if (res.code == 200) {
          this.storageData = res.data
        } else {
          alert('获取数据失败')
        }
      })
    },
    loadGoodstype() {
      this.$http.get('/goodstype/list').then(res => {
        console.log(res)
        if (res.code == 200) {
          this.goodstypeData = res.data
        } else {
          alert('获取数据失败')
        }
      })
    },
    loadSource() {
      this.$http.get('/source/list').then(res => {
        console.log(res)
        if (res.code == 200) {
          this.sourceData = res.data
        } else {
          alert('获取数据失败')
        }
      })
    }
  },
  beforeMount() {
    this.loadStorage()
    this.loadGoodstype()
    this.loadSource()
    this.loadPost()
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__body-wrapper {
  overflow: hidden !important;
}
::v-deep .avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .el-upload:hover {
    border-color: #409eff;
  }

  img {
    width: 38px;
    height: 38px;
    display: block;
  }
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
</style>
